# -*- coding: UTF-8 -*-
import md5
import os

from pyramid.view import view_config
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPFound
from sqlalchemy import and_, or_, desc

from pyramid.security import (
        remember,
        forget,
        IAuthenticationPolicy,
        )

from ..models.meta import (
    DBSession,
    )

from ..models.models import (
    BusinessUser,
    Coupon
    )

from ..lib.utils import upload
from ..freedom.dateutil.parser import parse


@view_config(route_name='business_login')
def business_login(request):
    if request.method=="GET":
        return render_to_response('/front/business/login.html', {}, request = request)
    if request.method=="POST":
        #capcha check
        #for test comment first
        #if request.session['CONSTANT_Captcha'] != request.params.get('captcha'):
            #return render_to_response('/front/business/login.html', {'error':u'验证码错误!'}, request = request)

        login = request.params.get('name', '')
        password = request.params.get('password', '')
        if(login and password):
            user_q = DBSession().query(BusinessUser)
            users = user_q.filter(and_(BusinessUser.login == login, BusinessUser.password == md5.new(password).hexdigest())).all()
            if(users and len(users) == 1):
                request.session['businessuser_login'] = login
                request.session['businessuser_id'] = users[0].id
                headers = remember(request, 'role:business')
                return HTTPFound(location = request.route_url('business_page', page='index'), headers = headers)
            else:
                return render_to_response('/front/business/login.html', {'error':u'用户名或者密码不正确!'}, request = request)

@view_config(route_name='business_page', permission='business_view')
@view_config(route_name='business_edit_page', permission='business_view')
def business_page(request):
    exec('result = business_%s(request)' % request.matchdict.get('page') or 'index')
    return result

def business_index(request):
    #get business info
    login = request.session['businessuser_login']
    user_q = DBSession().query(BusinessUser)
    businessuser = user_q.filter(BusinessUser.login == login).first()
    return render_to_response('/front/business/index.html', {'businessuser':businessuser}, request = request)

def business_info(request):
    tmpl_context = {}
    user_q = DBSession().query(BusinessUser)
    if 'id' not in request.params:
        login = request.session['businessuser_login']
        user = user_q.filter(BusinessUser.login == login).first()
    else:
        user = user_q.get(int(request.params.get('id')))
        user.companyname = request.params.get('companyname')
        user.businesstype = int(request.params.get('businesstype'))
        user.email = request.params.get('email')
        user.contactname = request.params.get('contactname')
        user.contacttel = request.params.get('contacttel')
        user.qq = request.params.get('qq')
        user.othercontacttool = request.params.get('othercontacttool')
        user.address = request.params.get('address')
        user.introduce = request.params.get('introduce')
        user.special = request.params.get('special')

        uploadfilename = upload(request.params.get('picture'), _getuploadpath(request))
        user.picture = uploadfilename and os.path.join(_getuploadurlpath(request),uploadfilename) or user.picture 
        
        tmpl_context['info'] = u'更新成功'

    tmpl_context['businessuser'] = user

    return render_to_response('/front/business/info.html', tmpl_context, request = request)


def business_couponpublish(request):
    couponid = int(request.matchdict.get('id') or -1)

    #get current business user info
    user_q = DBSession().query(BusinessUser)

    login = request.session['businessuser_login']
    user = user_q.filter(BusinessUser.login == login).first()

    #submit from add/edit
    if 'form.submitted' in request.params:
        coupon = Coupon()
        #edit
        if 'id' in request.params:
            coupon_q = DBSession.query(Coupon)
            coupon = coupon_q.get(int(request.params.get('id')))
        #new
        coupon.name = request.params.get('name')
        coupon.coupontype = request.params.get('coupontype')
        coupon.startdate = parse(request.params.get('startdate'))
        coupon.enddate = parse(request.params.get('enddate'))
        coupon.number = request.params.get('number')
        coupon.rule = request.params.get('rule')
        uploadfilename = upload(request.params.get('picture'), _getuploadpath(request))
        coupon.picture = uploadfilename and os.path.join(_getuploadurlpath(request), uploadfilename) or (coupon.picture or '')
        coupon.shortdetail = request.params.get('shortdetail')
        coupon.detail = request.params.get('detail')
        coupon.status = request.params.get('action') == 'publish' and 2 or 1
        coupon.businessuser = user

        DBSession.add(coupon)
        
        return HTTPFound(location = request.route_url('business_page', page='allcoupons'))
    #first visit
    else:
        tmpl_context = {}
        #get the edit coupopn info
        if couponid!=-1:
            coupon_q = DBSession.query(Coupon)
            coupon = coupon_q.get(couponid)
            tmpl_context['coupon'] = coupon
        tmpl_context['businessuser'] = user
        return render_to_response('/front/business/couponpublish.html', tmpl_context, request = request)

def business_allcoupons(request):
    #get current business user info
    user_q = DBSession().query(BusinessUser)

    login = request.session['businessuser_login']
    user = user_q.filter(BusinessUser.login == login).first()

    return render_to_response('/front/business/allcoupons.html', {'businessuser':user}, request = request)

def business_api_allcoupons(request):
    coupon_q = DBSession.query(Coupon)
    coupons = coupon_q.filter(Coupon.businessUser_id == request.session['businessuser_id']).filter(Coupon.deleted == False).all()
    tmpl_context = {}
    tmpl_context['Rows'] = coupons
    tmpl_context['TotalRows'] = len(coupons)
    #tmpl_context['TotalRows'] =5 
    return render_to_response('json', tmpl_context, request = request)

def business_deletecoupon(request):
    couponid = int(request.matchdict.get('id') or -1)
    coupon = DBSession.query(Coupon).get(couponid)
    coupon.deleted = True
    return HTTPFound(location = request.route_url('business_page', page='allcoupons'))


def _getuploadpath(request):
    login = request.session['businessuser_login']
    upload_path = request.registry.settings.get('adminupload.root')
    return os.path.join(upload_path, login)

def _getuploadurlpath(request):
    login = request.session['businessuser_login']
    upload_path='/static/admin/upload/'
    return os.path.join(upload_path, login)
